package com.kb.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.kb.common.MeException;
import com.kb.dto.HubCreateQuote;
import com.kb.service.HubService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@DS("master")
@Service
public class HubServiceImpl implements HubService {
    private static final Logger log = LoggerFactory.getLogger(HubServiceImpl.class);

//    private static final String URL = "http://pre.ichub.com/api/general-gateway/graphql";
//    private static final String API_KEY = "b735b7e2-5873-40c0-a2d2-a2ffcc30b568";

    private static final String URL = "http://openapi.ichub.com/api/general-gateway/graphql";
    private static final String API_KEY = "421327dd-fa6a-40d2-a881-a3208376e417";


    @Override
    public String getHubToken() throws MeException {
        String body = "{\"query\": \"{ login(input: { user_name: \\\"SZKingbrother\\\", password: \\\"KBOM2024\\\" }) {   data {     token     expires_at   } }}\"}";
//        String body = "{\"query\": \"{ login(input: { user_name: \\\"TEST-ICHUB\\\", password: \\\"123456.\\\" }) {   data {     token     expires_at   } }}\"}";
        Map<String, String> headers = new HashMap<>();
        headers.put("API-KEY", API_KEY);

        HttpResponse response = HttpRequest.post(URL)
                .body(JSONUtil.toJsonStr(body))  // 设置请求体
                .addHeaders(headers)  // 设置请求头，表示发送的是JSON数据
                .execute();  // 执行请求
        if (!Objects.equals(response.getStatus(), HttpStatus.HTTP_OK)) {
            throw new MeException("getInfoByPartNumber(),请求异常：" + response.body());
        }
        JSONObject jsonObject = JSONObject.parseObject(response.body());

        // 解析 JSON
        JSONObject jsonResponse = new JSONObject(jsonObject);
        JSONObject data = jsonResponse.getJSONObject("data");
        if (Objects.isNull(data)) {
            log.info("请求返回数据:{}", JSONUtil.toJsonStr(response.body()));
            return null;
        }
        JSONObject login = data.getJSONObject("login");
        JSONObject loginData = login.getJSONObject("data");
        // 提取 token 值
        return loginData.getString("token");
    }

    @Override
    public JSONObject getHubquote(Map<String, Object> map) throws MeException {

        String Token = this.getHubToken();
        Object keyword = map.get("keyWord");

//        String body ="{publishList(input:{page_size:30,current:1,type:1,keyword:\"XTR111AIDRCT\",start_time:1673930900,end_time:1731483505}){msg,code,data{list{object_id,ichub_part_number,part_number,part_brand,coo,packing,date_code,lead_time,description,updated_at,moq,mpq,qty,price{price_qty,price_break}},pagination{current,page_size,total}}}}";
//        String body = "{\"query\":\"{\\r\\n  publishList(input: {page_size: 30, current: 1, type: 1, keyword: \\\"" + keyword + "\\\"}) {\\r\\n    msg\\r\\n    code\\r\\n    data {\\r\\n      list {\\r\\n\\tobject_id\\r\\n        ichub_part_number\\r\\n        part_number\\r\\n        part_brand\\r\\n        coo\\r\\n        packing\\r\\n        date_code\\r\\n        lead_time\\r\\n        description\\r\\n        updated_at\\r\\n        moq\\r\\n        mpq\\r\\n        qty\\r\\n        price {\\r\\n          price_qty\\r\\n          price_break\\r\\n        }\\r\\n      }\\r\\n      pagination {\\r\\n        current\\r\\n        page_size\\r\\n        total\\r\\n      }\\r\\n    }\\r\\n  }\\r\\n}\",\"variables\":{}}";
        String body = "{\"query\":\"query publishList($input: PublishQueryPaginationRequest){\\r\\n    publishList(input: $input){\\r\\n        ...comparisonFields \\r\\n  }\\r\\n }\\r\\n fragment comparisonFields on general_page_result{\\r\\n    msg\\r\\n    code\\r\\n    data {\\r\\n      list {\\r\\n        object_id\\r\\n        ichub_part_number\\r\\n        part_number\\r\\n        part_brand\\r\\n        coo\\r\\n        packing\\r\\n        date_code\\r\\n        lead_time\\r\\n        description\\r\\n        updated_at\\r\\n        moq\\r\\n        mpq\\r\\n        qty\\r\\n        price {\\r\\n          price_qty\\r\\n          price_break\\r\\n        }\\r\\n      }\\r\\n      pagination {\\r\\n        current\\r\\n        page_size\\r\\n        total\\r\\n      }\\r\\n    }\\r\\n  }\\r\\n\",\"variables\":{\"input\":{\"page_size\":30,\"current\":1,\"type\":1,\"keyword\":\"" + keyword + "\",\"is_exact\":true}}}";



        Map<String, String> headers = new HashMap<>();
        headers.put("API-KEY", API_KEY);
        headers.put("X-Session-Token", Token);

        HttpResponse response = HttpRequest.post(URL)
                .body(body)  // 设置请求体
                .addHeaders(headers)  // 设置请求头，表示发送的是JSON数据
                .execute();  // 执行请求
        if (!Objects.equals(response.getStatus(), HttpStatus.HTTP_OK)) {
            throw new MeException("getHubquote(),请求异常：" + response.body());
        }
        JSONObject jsonObject = JSONObject.parseObject(response.body());
        return jsonObject;
    }

    public String formatJsonWithoutKeyQuotes(String jsonString) {
        StringBuilder result = new StringBuilder();
        result.append("[");

        // 假设jsonString已经是一个有效的JSON数组字符串，我们只需要找到每个对象和键值对。
        // 由于我们不能直接使用JSON库，这里我们使用简单的字符串操作来模拟这个过程。
        // 注意：这种方法非常脆弱，并且很容易受到输入格式变化的影响。

        // 为了简化，我们假设输入字符串是格式良好的，并且没有嵌套的数组或对象。
        String[] objects = jsonString.substring(1, jsonString.length() - 1).split("\\},\\{"); // 分割对象
        for (int i = 0; i < objects.length; i++) {
            String object = "{" + objects[i]; // 还原被分割的括号
            String[] keyValuePairs = object.substring(1, object.length() - 1).split(","); // 分割键值对
//            result.append("{");
            for (int j = 0; j < keyValuePairs.length; j++) {
                String keyValuePair = keyValuePairs[j];
                String[] parts = keyValuePair.split(":"); // 分割键和值
                String key = parts[0].trim().replace("\"", ""); // 获取键并去除双引号
                String value = parts[1].trim(); // 获取值（可能带有双引号）

                // 如果值是字符串，则添加转义的双引号；否则，直接添加值。
                if (value.startsWith("\"") && value.endsWith("\"")) {
                    value = value.substring(1, value.length() - 1).replace("\"", "\\\""); // 去除外部双引号并转义内部双引号
                    value ="\\"+ "\"" + value +"\\"+ "\""; // 重新添加双引号

                }

                result.append(key).append(":").append(value);
                if (j < keyValuePairs.length - 1) {
                    result.append(",");
                }
            }
            result.append("}");
            if (i < objects.length - 1) {
                result.append(",");
            }
        }

        result.append("]");
        return result.toString();
    }
    @Override
    public JSONObject getInquiry(List<HubCreateQuote> hubCreateQuote) throws MeException {

        String Token = this.getHubToken();
        String jsonStr = JSONUtil.toJsonStr(hubCreateQuote);

        String collect = this.formatJsonWithoutKeyQuotes(jsonStr);

        String body = "{\"query\":\"mutation {\\r\\n  bizRfqLineCreate(input: {\\r\\n    \\tdata_items: "+collect+"}) {\\r\\n    ids\\r\\n  }\\r\\n}\"}";
//        String body1 = "{\"query\":\"mutation {\\r\\n  bizRfqLineCreate(input: {\\r\\n    \\tdata_items: [{part_number: \\\"CLEX2\\\",\\r\\n        part_brand: \\\"brand052001\\\", qty: 2, original_line_code:\\\"123\\\"}]}) {\\r\\n    ids\\r\\n  }\\r\\n}\"}";
        Map<String, String> headers = new HashMap<>();
        headers.put("API-KEY", API_KEY);
        headers.put("X-Session-Token", Token);

        HttpResponse response = HttpRequest.post(URL)
                .body(body)  // 设置请求体
                .addHeaders(headers)  // 设置请求头，表示发送的是JSON数据
                .execute();  // 执行请求
        if (!Objects.equals(response.getStatus(), HttpStatus.HTTP_OK)) {
            throw new MeException("getInquiry(),请求异常：" + response.body());
        }
        JSONObject jsonObject = JSONObject.parseObject(response.body());
        return jsonObject;
    }


    @Override
    public JSONObject getQuotation(Map<String, Object> map) throws MeException {

        String Token = getHubToken();
        Object rfqOriginalLineCode = map.get("rfqOriginalLineCode");

        String body = "{\"query\":\"{\\r\\n  bizQfrLineList(input:{rfq_original_line_code:\\\""+rfqOriginalLineCode+"\\\"}){\\r\\n  \\tmsg\\r\\n    code\\r\\n    data {\\r\\n      list {\\r\\n        \\r\\n\\t\\tqfr_line_code\\r\\npart_number\\r\\npart_brand\\r\\nqty\\r\\nprice\\r\\ncurrency\\r\\ntax_name\\r\\ndate_code\\r\\nlead_time\\r\\nlocation\\r\\npacking\\r\\ncoo\\r\\ndescription\\r\\nmoq\\r\\nexpiry\\r\\ncreated_at\\r\\n      }\\r\\n    }\\r\\n  }\\r\\n}\"}";
        Map<String, String> headers = new HashMap<>();
        headers.put("API-KEY", API_KEY);
        headers.put("X-Session-Token", Token);

        HttpResponse response = HttpRequest.post(URL)
                .body(body)  // 设置请求体
                .addHeaders(headers)  // 设置请求头，表示发送的是JSON数据
                .execute();  // 执行请求
        if (!Objects.equals(response.getStatus(), HttpStatus.HTTP_OK)) {
            throw new MeException("getQuotation(),请求异常：" + response.body());
        }
        JSONObject jsonObject = JSONObject.parseObject(response.body());
        return jsonObject;
    }

}
